const _ = require("lodash");
const fs = require("fs");
const path = require("path");

// ✅ ESM 兼容
const esm = require("esm");
const requireModule = esm(module);

// ✅ 模块导入
const checkAccuracy = requireModule("./utils/checkAccuracy.js");
const { readAllValues } = requireModule("../awakened-potential/helpers/readAllValues.js");
const { getStrategyByName } = require("./strategies/strategyManager");

// ✅ 读取历史开奖数据（m 为澳门）
const allValues = readAllValues("m");

// ✅ 使用的策略
const strategyName = "S6";
const select32Numbers = getStrategyByName(strategyName);

// ✅ 滑动窗口设置
const useWindow = true;
const windowSize = 31;

// ✅ 所有可能的号码
const allNumbers = Array.from({ length: 49 }, (_, i) =>
  (i + 1).toString().padStart(2, "0")
);

// ✅ 统计变量
let predictResults = [];
let correct = 0;
let maxWrongStreak = 0;
let currentWrongStreak = 0;

// ✅ 用于记录每次不中的连续错误长度
let wrongStreakList = [];

// ✅ 遍历开奖数据
allValues.forEach((item, index) => {
  const temp = useWindow
    ? allValues.slice(Math.max(0, index - windowSize), index)
    : allValues.slice(0, index);
  if (temp.length === 0) return;

  const predictNumbers = select32Numbers(temp);
  const isHit = checkAccuracy(predictNumbers, item.number);

  predictResults.push({
    index,
    date: item.time,
    actual: item.number,
    predict: predictNumbers,
    hit: isHit,
  });

  if (isHit) {
    if (currentWrongStreak > 0) {
      wrongStreakList.push(currentWrongStreak); // 记录本次不中的 streak
    }
    correct++;
    currentWrongStreak = 0;
  } else {
    currentWrongStreak++;
    maxWrongStreak = Math.max(maxWrongStreak, currentWrongStreak);
  }
});

// ✅ 最后一段连续不中也要统计
if (currentWrongStreak > 0) {
  wrongStreakList.push(currentWrongStreak);
}

// ✅ 统计每种连续不中次数的出现频次
const streakFrequencyMap = _.countBy(wrongStreakList);

// ✅ 输出结果统计
const total = predictResults.length;
const accuracy = ((correct / total) * 100).toFixed(2);

console.log(`\n策略：${strategyName}`);
console.log(`总预测期数: ${total}`);
console.log(`命中次数: ${correct}`);
console.log(`✅ 准确率: ${accuracy}%`);
console.log(`❌ 最大连续错误: ${maxWrongStreak}`);

// ✅ 输出连续不中统计表
console.log("\n❌ 各类连续不中次数出现频率：");
console.log("连续错误次数\t出现次数");
for (let i = 1; i <= maxWrongStreak; i++) {
  const count = streakFrequencyMap[i] || 0;
  console.log(`${i} 次\t\t${count} 次`);
}
